package com.smart.service.im;

import com.alibaba.fastjson2.JSONObject;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.manager.member.entities.models.MemberProfileMain;
import com.smart.manager.system.repository.ConfigRepository;
import io.github.doocs.im.ImClient;
import io.github.doocs.im.model.request.AccountImportRequest;
import io.github.doocs.im.model.response.AccountImportResult;
import io.github.doocs.im.util.SigUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 */
@Service
@RequiredArgsConstructor
@Log4j2
public class ImService {

    private final ConfigRepository configRepository;


    public ImClient getClient() {
        JSONObject jsonObject = configRepository.readCache(SmartConstant.TENCENT_IM_CFG);
        long appId = jsonObject.getLongValue("appId");
        String appSecret = jsonObject.getString("appSecret");
        String userId = jsonObject.getString("masterId");
        return ImClient.getInstance(appId, userId, appSecret);
    }

    /**
     * @param memberId 根据会员编号获取用户IM身份令牌
     * @return {@code String}
     */
    public String getUserSign(Long memberId) {
        JSONObject jsonObject = configRepository.readCache(SmartConstant.TENCENT_IM_CFG);
        long appId = jsonObject.getLongValue("appId");
        String appSecret = jsonObject.getString("appSecret");
        return SigUtil.genUserSig(appId, appSecret, String.valueOf(memberId),  7 * 24 * 60 * 60L);
    }


    public void createImAccount(MemberProfileMain member) {
        try {
            ImClient client = getClient();
            AccountImportRequest request = AccountImportRequest.builder()
                    .userId(String.valueOf(member.getId()))
                    .faceUrl(member.getAvatar()).nick(member.getNickName()).build();

            AccountImportResult result = client.account.accountImport(request);
            if (result.getErrorCode().equals(0)) {
                member.setImStatus(true) ;
            }
        } catch (Exception e) {
            throw new RuntimeException("IM账号创建失败:" + e.getMessage());
        }
    }
}
